package ctp.utils;

import org.apache.commons.collections15.Transformer;

import ctp.ctpgraph.CTPGraph;
import ctp.ctpgraph.Edge;
import ctp.ctpgraph.EdgeRandom;
import ctp.ctpgraph.Vertex;
import ctp.statesgraph.State;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseGraph;

public class GraphUtils {
	public static Graph<Vertex, Edge> buildKernel(CTPGraph ctpGraph, State state, boolean includeUnknown) {
		Graph<Vertex,Edge> kernel = new SparseGraph<Vertex, Edge>();
		for (Edge edge : ctpGraph.getGraph().getEdges()) {
			kernel.addEdge(edge, ctpGraph.getGraph().getIncidentVertices(edge));
		}
		
		for (Vertex vertex : ctpGraph.getGraph().getVertices()) {
			for (Edge edge : ctpGraph.getGraph().getIncidentEdges(vertex)) {
				if (includeUnknown && state.getUnknownEdges().contains(edge)) {
					kernel.removeVertex(vertex);
					continue;
				} else if (state.getBlockedEdges().contains(edge)) {
					kernel.removeEdge(edge);
					continue;
				}
			}
		}
		return kernel;
	}
	
	
	public static double dijkstraOnGraph(Graph<Vertex, Edge> graph, Vertex source, Vertex target) {
		
		Transformer<Edge, Double> cost = new Transformer<Edge, Double>() {
			@Override
			public Double transform(Edge e) {
				return e.getCost();
			}
		};
		
		DijkstraShortestPath<Vertex, Edge> dij = new DijkstraShortestPath<Vertex, Edge>(graph, cost, true);
		
		Double dist = (Double) dij.getDistance(source, target);
		return dist.doubleValue();
	}	
}
